package com.example.im.distribute

import cc.vv.lkbasecomponent.util.LKStringUtil
import cc.vv.lkimcomponent.lkim.bean.LKIMMessage
import cc.vv.lkimcomponent.lkim.bean.venum.LKIMChatType
import com.example.baselibrary.R
import com.example.baselibrary.db.dao.AccountDao
import com.example.baselibrary.db.dao.GroupDao
import com.example.baselibrary.db.table.AccountTable
import com.example.baselibrary.db.table.GroupTable
import com.example.im.IMReceiveService
import com.example.im.inform.InformOperate
import com.example.util.finallist.IMExtKey

/**
 * 常规消息
 * @author  chaohaipeng  on 2018/7/23.
 */
class DefMessageDistribute {
    private object mHolder {
        val instance = DefMessageDistribute()
    }
    companion object {
        fun getInstance(): DefMessageDistribute {
            return mHolder.instance
        }
    }
    /**
     * 消息分类处理
     *
     * @param lkimMessages 消息体集合
     */
    @Synchronized
    fun distribute(lkimMessages: List<LKIMMessage>?) {
        if (lkimMessages!=null){
            initAccountInfoTable(lkimMessages)
            for (lkimMessage in lkimMessages) {
                IMReceiveService.getInstance().sendInsertCache("", lkimMessage, false)
               InformOperate.getInstance().createIMInform(lkimMessage)
            }
            IMReceiveService.getInstance().sendRefreshConversation()
        }

    }
    /**
     * 更新联系人信息表数据
     *
     * @param lkimMessages 消息体集合
     */
    private fun initAccountInfoTable(lkimMessages: List<LKIMMessage>) {
        for (lkimMessage in lkimMessages) {
            /*用户信息维护*/
            val accountTable = AccountTable(lkimMessage.fromAccount, lkimMessage.getAttribute(IMExtKey.EXTKEY_NICK, LKStringUtil.getString(R.string.app_name)), lkimMessage.getAttribute(IMExtKey.EXTKEY_AVATAR, ""), lkimMessage.getAttribute(IMExtKey.EXTKEY_MEMBERID, ""), lkimMessage.getAttribute(IMExtKey.EXTKEY_POSITION, ""))
            AccountDao.getInstance().createOrUpdate(accountTable)

            /*群组信息维护*/
            if (LKIMChatType.GroupChat == lkimMessage.lkimChatType) {
                val groupTable = GroupTable(lkimMessage.toAccount,
                        lkimMessage.getAttribute(IMExtKey.EXTKEY_GROUPNICK, LKStringUtil.getString(R.string.app_name)),
                        lkimMessage.getAttribute(IMExtKey.EXTKEY_GROUPAVATAR, ""))
                GroupDao.getInstance().updateGroup(groupTable)
            }
        }
    }
}